package prototipo.server.logic.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import prototipo.server.logic.exception.ExceptionLogic;

public class Password implements PasswordIF {

	final static private String ALGORITHM = "MD5";
	private byte[] encryptedPassword;

	public Password(String newPass) throws ExceptionLogic {
		this();
		this.encryptPassword(newPass);
	}

	public Password() {
	}

	/**
	 * @param password
	 *            the String is going to be encrypted.
	 * @throws ExceptionLogic
	 */
	public void encryptPassword(String password) throws ExceptionLogic {
		if (validatePassword(password)) {
			MessageDigest md;
			try {
				md = MessageDigest.getInstance(ALGORITHM);
				this.encryptedPassword = md.digest(password.getBytes());
				md.reset();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
	}

	private boolean validatePassword(String password) throws ExceptionLogic {
		if (password == null)
			throw new ExceptionLogic("Senha vazia.", new Throwable(
					"Password String is null"));
		if (password.length() < 8)
			throw new ExceptionLogic("Senha deve ter no minimo 8 caracteres.",
					new Throwable("Password's length is under 8 characters."));
		return true;
	}

	/**
	 * @return the encryptedPassword
	 */
	public byte[] getEncryptedPassword() {
		return encryptedPassword;
	}

	/**
	 * @param encryptedPassword
	 *            the encryptedPassword to set
	 * @throws ExceptionLogic 
	 */
	public void setEncryptedPassword(byte[] encryptedPassword) throws ExceptionLogic {
		if (encryptedPassword == null)
			throw new ExceptionLogic("Senha criptografada vazia.",
					new Throwable("EncryptedPassword's byte[] is null"));
		this.encryptedPassword = encryptedPassword;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(encryptedPassword);
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Password))
			return false;
		Password other = (Password) obj;
		if (!Arrays.equals(encryptedPassword, other.encryptedPassword))
			return false;
		return true;
	}

	public String toString() {
		String str = "";
		for (byte b : this.encryptedPassword) {
			str += String.format("%s", String.valueOf(b));
		}
		return str;
	}
}
